<template>
  <div class="delivery-tasks">
    <div class="header">
      <h2>配送任务管理</h2>
      <div class="actions">
        <el-button type="primary" @click="refreshTasks">刷新数据</el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="配送编号">
          <el-input v-model="filterForm.delivery_number" placeholder="配送编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="filterForm.order_number" placeholder="订单编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="filterForm.customer_name" placeholder="客户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="filterForm.status" 
            placeholder="选择状态" 
            clearable
            popper-class="status-select-dropdown"
          >
            <el-option label="全部" value="" />
            <el-option label="已分配" value="assigned" />
            <el-option label="配送中" value="delivering" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select 
            v-model="filterForm.priority" 
            placeholder="选择优先级" 
            clearable
            popper-class="priority-select-dropdown"
          >
            <el-option label="全部" value="" />
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 配送任务列表 -->
    <el-table 
      v-loading="loading"
      :data="displayTasks" 
      style="width: 100%"
      border
      stripe
      highlight-current-row
    >
      <el-table-column prop="delivery_number" label="配送编号" width="150" sortable />
      <el-table-column prop="order_number" label="关联订单" width="150" sortable />
      <el-table-column prop="customer_name" label="客户名称" width="120" />
      <el-table-column prop="address" label="配送地址" min-width="200" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="80">
        <template #default="scope">
          <el-tag 
            :type="scope.row.priority === 'high' ? 'danger' : scope.row.priority === 'medium' ? 'warning' : 'info'"
          >
            {{ scope.row.priority === 'high' ? '高' : scope.row.priority === 'medium' ? '中' : '低' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="estimated_delivery_time" label="预计配送时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click.stop="handleViewDetail(scope.row)">查看</el-button>
          <el-button 
            v-if="scope.row.status === 'assigned'"
            size="small" 
            type="success" 
            @click.stop="handleStartDelivery(scope.row)"
          >
            开始配送
          </el-button>
          <el-button 
            v-if="scope.row.status === 'delivering'"
            size="small" 
            type="success" 
            @click.stop="handleCompleteDelivery(scope.row)"
          >
            完成配送
          </el-button>
          <el-button 
            v-if="scope.row.status === 'assigned' && scope.row.rejection_count < 2"
            size="small" 
            type="danger" 
            @click.stop="handleRejectTask(scope.row)"
          >
            拒绝任务
          </el-button>
          <el-tag 
            v-if="isForceAssignment(scope.row)" 
            type="danger"
            effect="dark"
            size="small"
          >
            强制分配
          </el-tag>
        </template>
      </el-table-column>
      <!-- 在表格中添加客户联系电话列 -->
      <el-table-column prop="sales_order_detail.phone" label="联系电话" width="120">
        <template #default="scope">
          {{ scope.row.sales_order_detail?.phone || '无' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="safeTotalItems"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 拒绝任务对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝配送任务"
      width="40%"
    >
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="拒绝原因" required>
          <el-select v-model="rejectForm.reason" placeholder="请选择拒绝原因">
            <el-option label="时间冲突" value="time_conflict" />
            <el-option label="距离过远" value="distance_too_far" />
            <el-option label="工作量过大" value="workload_too_high" />
            <el-option label="其他原因" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细说明">
          <el-input 
            type="textarea" 
            v-model="rejectForm.note" 
            placeholder="请输入详细说明"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="submitRejectTask">确认拒绝</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 任务详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="配送任务详情" width="70%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="配送编号">{{ currentTask.delivery_number }}</el-descriptions-item>
        <el-descriptions-item label="关联订单">{{ currentTask.order_number }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentTask.customer_name }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentTask.sales_order_detail?.phone || '无' }}</el-descriptions-item>
        <el-descriptions-item label="配送地址" :span="2">{{ currentTask.address }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentTask.status)">{{ getStatusText(currentTask.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优先级">
          <el-tag :type="currentTask.priority === 'high' ? 'danger' : currentTask.priority === 'medium' ? 'warning' : 'info'">
            {{ currentTask.priority === 'high' ? '高' : currentTask.priority === 'medium' ? '中' : '低' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="预计配送时间">{{ currentTask.estimated_delivery_time }}</el-descriptions-item>
        <el-descriptions-item label="实际配送时间">{{ currentTask.actual_delivery_time || '未完成' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentTask.note || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 订单商品列表 -->
      <div class="order-items" style="margin-top: 20px;">
        <h3>订单商品</h3>
        <el-table :data="currentTask.sales_order_detail?.items || []" border stripe>
          <el-table-column prop="product_name" label="商品名称" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="unit_price" label="单价" width="100">
            <template #default="scope">
              ¥{{ scope.row.unit_price }}
            </template>
          </el-table-column>
          <el-table-column prop="total_price" label="小计" width="100">
            <template #default="scope">
              ¥{{ scope.row.total_price }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 配送状态历史 -->
      <div class="status-history" style="margin-top: 20px;">
        <h3>配送状态历史</h3>
        <el-timeline>
          <el-timeline-item
            v-for="record in currentTask.status_records"
            :key="record.id"
            :timestamp="record.created_at"
            :type="getStatusType(record.status)"
          >
            <h4>{{ getStatusText(record.status) }}</h4>
            <p>操作人: {{ record.operator_name }}</p>
            <p>备注: {{ record.note || '无' }}</p>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDeliveryTasks, updateDeliveryTaskStatus, rejectDeliveryTask } from '@/api/delivery'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/stores/user'

// 获取用户状态
const userStore = useUserStore()

// 状态数据
const loading = ref(false)
const tasks = ref([])
const allTasks = ref([]) // 存储所有任务数据
const currentPage = ref(1)
const pageSize = ref(5) // 默认改为每页5条
const totalItems = ref(0)
const detailDialogVisible = ref(false)
const currentTask = ref({})

// 确保总数是有效的数字
const safeTotalItems = computed(() => {
  return allTasks.value.length
})

// 计算当前页显示的任务
const displayTasks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allTasks.value.slice(start, end)
})

// 筛选表单
const filterForm = ref({
  delivery_number: '',
  order_number: '',
  customer_name: '',
  status: '',  // 确保初始值为空字符串
  priority: '' // 确保初始值为空字符串
})

// 状态选项
const statusOptions = ref([
  { value: 'assigned', label: '已分配' },
  { value: 'delivering', label: '配送中' },
  { value: 'completed', label: '已完成' }
])

// 优先级选项
const priorityOptions = ref([
  { value: 'high', label: '高' },
  { value: 'medium', label: '中' },
  { value: 'low', label: '低' }
])

// 拒绝任务相关
const rejectDialogVisible = ref(false)
const rejectForm = ref({
  task_id: null,
  delivery_number: '',
  reason: '',
  note: ''
})

// 添加计算属性判断是否为强制分配
const isForceAssignment = (task) => {
  return task.rejection_count >= 2 && task.status === 'assigned';
}

// 获取任务列表
const fetchTasks = async () => {
  loading.value = true
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    // 构建查询参数，获取所有数据
    const params = {
      page_size: 1000 // 获取所有数据
    }
    
    // 如果是配送员角色，添加配送员ID作为筛选条件
    if (userStore.role === 'deliveryman' && userStore.user && userStore.user.id) {
      params.deliveryman = userStore.user.id
    }
    
    console.log('发送查询参数:', params)
    const response = await getDeliveryTasks(params)
    console.log('API响应数据:', response)
    
    // 健壮的数据处理
    if (response && response.data) {
      console.log('解析响应数据:', JSON.stringify(response.data))
      
      // 处理不同的响应数据结构
      if (response.data.code === 200 && response.data.data) {
        allTasks.value = response.data.data.items || []
      } else if (response.data.items && Array.isArray(response.data.items)) {
        allTasks.value = response.data.items
      } else if (response.data.results && Array.isArray(response.data.results)) {
        allTasks.value = response.data.results
      } else if (Array.isArray(response.data)) {
        allTasks.value = response.data
      } else {
        allTasks.value = []
      }
      
      // 应用筛选条件
      filterTasks()
      
    } else {
      console.warn('API响应为空或格式不正确:', response)
      allTasks.value = []
    }
  } catch (error) {
    console.error('获取配送任务失败:', error)
    ElMessage.error(error.response?.data?.message || '获取配送任务列表失败')
    allTasks.value = []
  } finally {
    loading.value = false
  }
}

// 筛选任务
const filterTasks = () => {
  let filtered = [...allTasks.value]
  
  // 应用筛选条件
  if (filterForm.value.delivery_number) {
    filtered = filtered.filter(task => 
      task.delivery_number && task.delivery_number.includes(filterForm.value.delivery_number)
    )
  }
  
  if (filterForm.value.order_number) {
    filtered = filtered.filter(task => 
      task.order_number && task.order_number.includes(filterForm.value.order_number)
    )
  }
  
  if (filterForm.value.customer_name) {
    filtered = filtered.filter(task => 
      task.customer_name && task.customer_name.includes(filterForm.value.customer_name)
    )
  }
  
  // 修改状态筛选逻辑
  if (filterForm.value.status) {
    filtered = filtered.filter(task => task.status === filterForm.value.status)
  }
  
  // 修改优先级筛选逻辑
  if (filterForm.value.priority) {
    filtered = filtered.filter(task => task.priority === filterForm.value.priority)
  }
  
  // 更新过滤后的数据
  allTasks.value = filtered
}

// 开始配送
const handleStartDelivery = async (row) => {
  try {
    await ElMessageBox.confirm('确认开始配送该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await updateDeliveryTaskStatus(row.id, {
      status: 'delivering',
      note: '配送员开始配送'
    })
    
    ElMessage.success('已开始配送')
    fetchTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始配送失败:', error)
      ElMessage.error('开始配送失败')
    }
  }
}

// 完成配送
const handleCompleteDelivery = async (row) => {
  try {
    await ElMessageBox.confirm('确认完成该配送任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    await updateDeliveryTaskStatus(row.id, {
      status: 'completed',
      note: '配送员已完成配送'
    })
    
    ElMessage.success('配送任务已完成')
    fetchTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成配送失败:', error)
      ElMessage.error('完成配送失败')
    }
  }
}

// 拒绝任务
const handleRejectTask = (row) => {
  rejectForm.value = {
    task_id: row.id,
    delivery_number: row.delivery_number,
    reason: '',
    note: ''
  }
  rejectDialogVisible.value = true
}

// 提交拒绝任务
const submitRejectTask = async () => {
  if (!rejectForm.value.reason) {
    ElMessage.warning('请选择拒绝原因')
    return
  }
  
  try {
    await rejectDeliveryTask(rejectForm.value.task_id, {
      reason: rejectForm.value.reason,
      note: rejectForm.value.note
    })
    
    ElMessage.success('已拒绝该配送任务')
    rejectDialogVisible.value = false
    fetchTasks()
  } catch (error) {
    console.error('拒绝任务失败:', error)
    ElMessage.error('拒绝任务失败')
  }
}

// 状态显示相关
const getStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    assigned: 'warning',
    rejected: 'danger',
    delivering: 'primary',
    completed: 'success',
    cancelled: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    assigned: '已分配',
    rejected: '已拒绝',
    delivering: '配送中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1 // 只在手动点击筛选按钮时重置页码
  filterTasks()
}

// 重置筛选
const resetFilter = () => {
  // 确保重置为空字符串
  filterForm.value = {
    delivery_number: '',
    order_number: '',
    customer_name: '',
    status: '',
    priority: ''
  }
  currentPage.value = 1 // 重置时回到第一页
  // 重新获取所有数据
  fetchTasks()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 改变每页数量时重置到第一页
}

// 查看任务详情
const handleViewDetail = (row) => {
  currentTask.value = row
  detailDialogVisible.value = true
}

// 添加一个刷新数据的函数
const refreshTasks = () => {
  // 不重置筛选条件
  fetchTasks()
  ElMessage.success('数据已刷新')
}

// 生命周期钩子
onMounted(() => {
  // 初始化分页参数
  currentPage.value = 1
  pageSize.value = 5
  
  // 获取任务列表
  fetchTasks()
})
</script>

<style scoped>
.delivery-tasks {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-tip {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

/* 确保选择框正确显示选中文本 */
:deep(.el-select .el-input__inner) {
  text-align: left;
}
</style>